<template>
  <div class="home-my-area-wrap" >
        <van-nav-bar
		  title="选择所属区域"
		  left-arrow
		  fixed
		  @click-left="onClickLeft"
		/>

        <div class="input-ul" >
            <van-field
                v-model="address"
                readonly
                label-width="130px"
                label="请选择代理区域："
                :right-icon="goodCeilArrow"
                placeholder="请选择所属区域"
                @click="showPopup = true"
            />
            <div></div>
        </div>

        <div @click="handleToClick" class="confirm-btn active-btn" >确定</div>

        <!-- 地址 -->
        <van-popup v-model="showPopup" position="bottom">
            <van-cascader
            v-model="cascaderValue"
            title="请选择地址"
            :options="options"
            @close="showPopup = false"
            @change="onChange"
            @finish="onFinish"
            />

        </van-popup>

  </div>
</template>

<script>
import { goodCeilArrow } from '@/tool/static-img';
import { REGION_LIST } from '@/api/home';
import { UPDATE_LOCATION } from '@/api/home';
export default {
    data() {
        return {
            goodCeilArrow,
            address: '',

            // 地址
            showPopup: false,
            cascaderValue: '',
            options: [],
            tabIndex: 0,
        }
    },
    created() {
        // 初始化时加载省级数据
        this.fetchRegions(1, 0);
    },
    methods: {
        onClickLeft() {
            this.$router.back()
        },
        async fetchRegions(parentCode, level) {
            const res = await this.$http.get(REGION_LIST, {
                params: {
                    code: parentCode
                }
            })
                const {
                    data
                } = res;

                // 省级
                if(level === 0) {
                    data.forEach(item => {
                        this.options.push({
                            text: item.name,
                            value: item.code,
                            children: []
                        });
                    })
                } else if(level === 1) {
                    // 市级数据
                    const province = this.options.find(item => item.value === parentCode);
                    if (province) {
                        province.children = data.map(item => ({
                            text: item.name,
                            value: item.code,
                            children: []
                        }));
                    }
                } else if(level === 2) {
                    // 区/县级数据
                    this.options.forEach(province => {
                        const city = province.children.find(item => item.value === parentCode);
                        if (city) {
                            city.children = data.map(item => ({
                                text: item.name,
                                value: item.code,
                                children: []
                            }));
                        }
                    });
                }
        },
        // 选择器变化时的回调
        onChange(res) {
            this.tabIndex = res.tabIndex;
            if(this.tabIndex === 2) {
                return;
            }
            console.log(res, 'jj')
            //点击加载下一级回调
            this.getSpaceListAgain(res.selectedOptions, res.value);
        },
        getSpaceListAgain(selectedOptions, value) {
            this.$http.get(REGION_LIST, {
                params: {
                    code: value
                }
            })
            .then(res => {
                const {
                    data
                } = res;

                if(data && data.length) {
                    this.setOptions(selectedOptions, data);
                }
            })
        },
        setOptions(selectedOptions, data) {
            let _options = this.options;
            selectedOptions.forEach((item, index) => {
                if (index) {
                    //不是第一个则取下一级children
                    _options = _options.children;
                }
                _options = _options[_options.findIndex((_item) => _item.value === item.value)];
            });
            //找到最后一级
            _options.children = data.map((item) => {
                return {
                    text: item.name,
                    value: item.code,
                    children: this.tabIndex == 1 ? null : [],
                };
            });
        },
        onFinish({ selectedOptions }) {

            this.showPopup = false;

            this.selectAreaList = selectedOptions;

            selectedOptions = selectedOptions.filter(item => {

                return item.value !== 0;
            })

            console.log(selectedOptions, 'll')

            this.address = selectedOptions.map((option) => option.text).join('/');
        },
        // 确定
        handleToClick() {
            if(!this.selectAreaList.length) {
                this.$toast('请选择代理区域')
                return 
            }

            this.$http.post(UPDATE_LOCATION, {
                region_code: this.selectAreaList[2].value
            })
            .then(() => {

                this.$toast.success('设置成功');

                setTimeout(() =>{
                    this.$router.back()
                }, 500)
            })


        }
    }

}

</script>
<style lang="scss" >
.home-my-area-wrap{
    position: relative;
    min-height: 100vh;
    padding-top: 46px;
    background-color: #ffffff;
    box-sizing: border-box;
    .van-nav-bar .van-icon{
        color: #333333;
    }
    .van-nav-bar__arrow{
        font-size: 20px;
    }
    .van-hairline--bottom::after{
        display: none;
    }

    .confirm-btn{
        display: flex;
        align-items: center;
        justify-content: center;
        width: 6.06rem;
        height: 0.88rem;
        margin: auto;
        margin-top: 2.5rem;
        font-weight: 500;
        font-size: 0.32rem;
        color: #ffffff;
        border-radius: 0.44rem;
        background: linear-gradient( 135deg, #FF5851 0%, #E9011B 100%);
    }

}
</style>